package com.interesting.client.support.update;

import java.io.File;

import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.support.v4.app.FragmentManager;

import com.interesting.R;
import com.interesting.base.utils.Constant;
import com.interesting.client.UI.commonActivity.UIUtil;
import com.interesting.client.application.AppHolder;
import com.interesting.client.bean.VersionInfo;

public class UpdateUtil {
	/**
	 * 检查更新版本
	 */
	public static void checkVersion(final Context context, FragmentManager fm, final VersionInfo version) {

		float locationVersion = Float.valueOf(AppHolder.getInsatnce().getVersion(context));
		float serverVersion = Float.valueOf(version.getApkVersion());

		if (locationVersion < serverVersion) {
			// 发现新版本，提示用户更新
			UIUtil.showAlertDialog(fm, "新版本", version.getApkRemark(), "更新", "取消", new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// 开启更新服务UpdateService
					// 这里为了把update更好模块化，可以传一些updateService依赖的值
					// 如布局ID，资源ID，动态获取的标题,这里以app_name为例
					Intent updateIntent = new Intent(context, UpdateService.class);
					updateIntent.putExtra("title", context.getResources().getString(R.string.app_name));
					updateIntent.putExtra("downloadUrl", version.getApkURL());
					context.startService(updateIntent);
				}
			}, new OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});

		} else {
			File updateFile = new File(Constant.SD_DOWNLOAD_PATH, context.getResources().getString(R.string.app_name)
					+ ".apk");
			if (updateFile.exists()) {
				updateFile.delete();
			}
			UIUtil.showToast(context, "此版本为最新版");
		}
	}
}
